#
# Generate .h by .config
#

import sys
import os
import datetime

def _analyse (rowl):
    define = '#define '
    # bool
    if rowl[1] == 'y':
        return define + rowl[0]
    return define + rowl[0] + ' ' + rowl[1]

def generate (config, output):
    # get the path of script
    scriptpath = os.path.abspath(__file__)
    scriptpath = os.path.dirname(scriptpath)

    # read the template of .h
    template = ''
    with open(scriptpath + '/template.h', 'r') as file:
        template = file.read()

    # analysis .config
    content = ''
    with open(config, 'r') as file:
        for line in file:
            line = line.strip()
            if line != '' and not line.startswith('#'):
                line = line.removeprefix('CONFIG_')
                rowl = line.split('=')
                content += _analyse(rowl) + '\n'

    # package
    template = template.replace('${version}', '1.0.0')
    template = template.replace('${filename}', os.path.basename(output).removesuffix('.h').upper())
    template = template.replace('${time}', str(datetime.datetime.now()))
    template = template.replace('${content}', content)

    # output
    with open(output, 'w') as file:
        file.write(template)

def main ():
    if len(sys.argv) != 3:
        print('argument fault.')
        return -1
    
    generate(sys.argv[1], sys.argv[2])
    
    return 0

if __name__ == '__main__':
    sys.exit(main())
